package com.sl.plugin.step.script;

import cn.hutool.core.util.ObjectUtil;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.sl.core.engine.meta.ProcessCompDescriptorService;
import com.sl.core.engine.meta.impl.AbstractProcessCompDescriptor;
import com.sl.core.engine.meta.row.ProcessRowDescriptor;
import com.sl.core.engine.scripts.GroovyScriptExecutor;
import lombok.Getter;
import lombok.extern.slf4j.Slf4j;

import java.lang.reflect.Method;
import java.util.Collection;
import java.util.Map;

/**
 *
 */
@Getter
@Slf4j
public class GroovyCompDescriptor extends AbstractProcessCompDescriptor<
        GroovyComp, GroovyCompContext> implements ProcessCompDescriptorService {


//    @Override
//    protected ProcessCompService getComp() {
//        return new GroovyComp(this);
//    }
//
//    @Override
//    public ProcessCompContextService getContext() {
//        return new GroovyCompContext();
//    }


    @Override
    public void loadDescriptor(Map<String, Object> map) {
        //输入定义

        String script = getStrAttr("config.scripts");
        Map<String, Object> params = getMapAttr("params");
        Object o = null;
        Map<String, Object> inputJsonDefine = getJsonDefine("config.output");
        if (ObjectUtil.isNotNull(inputJsonDefine)) {
            ProcessRowDescriptor processRowDescriptor = buildResultProcessRowDescriptor(inputJsonDefine);
            if (ObjectUtil.isNotNull(processRowDescriptor)) {
                return;
            }
        }


        try {
            if (ObjectUtil.isNull(params)) {
                params = Maps.newHashMap();
            }
            o = executeTestScript(script, params);
        } catch (Exception e) {
            log.error("执行获取结果失败", e);
        }
        if (ObjectUtil.isNotNull(o)) {
            ProcessRowDescriptor processRowDescriptor = ProcessRowDescriptor.objectToRowMeta(o);
            setResultRowDescriptor(processRowDescriptor);
        }
    }

    protected Object executeTestScript(String script, Object params) {
        Method runMethod = GroovyScriptExecutor.INSTANCE.getRunMethod(script);
        Object[] resolver = null;
        if (params instanceof Collection<?> collection) {
            resolver = HandlerMethodArgumentResolver.resolverList(runMethod, collection);
        } else {
            resolver = HandlerMethodArgumentResolver.resolver(runMethod, Lists.newArrayList(params), params);
        }
        Object o = GroovyScriptExecutor.INSTANCE.executeScriptAndFormat(script, resolver);
        return o;
    }


    @Override
    public ProcessRowDescriptor getResultDescriptor(ProcessRowDescriptor rowDescriptor) {


        ProcessRowDescriptor rowMeta = getResultRowDescriptor();

        if (ObjectUtil.isNull(rowMeta) || rowMeta.isEmptyAndNotBasic()) {
            return rowDescriptor;
        }
        return rowMeta;
    }

}
